<?php
/**
 * Created by PhpStorm.
 * User: xiaoxin
 * Date: 2018/10/22 0022
 * Time: 17:18
 */

namespace app\index\controller;
use app\index\model\User;
use think\Controller;
use think\Loader;

class SafetySet extends Controller
{
	/**
	 * 安全设置主页
	 * @return mixed
	 */
	public function index(){
		return $this->fetch();
	}


	/**
	 * 修改密码主页
	 * @return mixed
	 */
	public function changePassword(){
	    return $this->fetch();
	}


	/**
	 * 更改密码方法
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function editPassword(){
		$data = input('post.');
		if (!session('uid')){
			$this->error('请先登陆');
		}
		$validate = Loader::validate('EditPassword');
		if(!$validate->check($data)){
			$this->error($validate->getError());
		}
		$res = User::where(['uid'=>session('uid'),'password'=>md5($data['password'])])->find();
		if ($res){
			$res = User::where('uid', session('uid'))
				->update(['password' => md5($data['newpassword'])]);
			if ($res){
				session(null);
				$this->success('更改成功');
			}else{
				$this->error('更改失败，请稍后再试');
			}
		}else{
			$this->error('对不起，不存在该用户');
		}
	}


	/**
	 * 更改手机号码主页
	 * @return mixed
	 */
	public function changePhone(){
		return $this->fetch();
	}


	/**
	 *更换手机号方法
	 */
	public function editPhone(){
		$data = input('post.');
		$validate = Loader::validate('AddUserCheck');
		if(!$validate->scene('phone')->check($data)){
			$this->error($validate->getError());
		}
		if (session('code')['num']==$data['phoneCode']){
			$res = User::where('uid', session('uid'))
				->update(['phone' => $data['phone']]);
			if ($res){
				session('code',null);
				$this->success('已更换');
			}else{
				$this->error('更换失败，请稍后在试');
			}
		}else{
			$this->error('手机验证码错误，请重新输入');
		}
	}
}